const storageService = require('../../services/storage');
const playerModeService = require('../../services/player_mode_service')
const shortcutModeService = require('../../services/shortcut_mode_service')
const advancedModeService = require('../../services/advanced_mode_service')
import * as comm from '../../utils/common';

// 获取 App 实例
const appInstance = getApp();

Page({
  data: {
    isExpanded: false,
    devices: [],
    groups: [],
    manualModeRgbwCache: {}, // 新增：用于缓存手动模式下的RGBW值
    buttonHandlers: {
      0: function () {
        // 跳转到设备搜索页面
        wx.navigateTo({
          url: '/packageAddDevice/pages/device_search/device_search',
        })
      },
      1: function () {
        // 跳转到编组设置页面
        wx.navigateTo({
          url: '/packageGroup/pages/group_settings/group_settings',
        })
      },
      2: function () {
        this.setData({
          showCloudSyncDialog: true
        })
      },
      3: function () {
        wx.navigateTo({
          url: '/pages/other/other',
        })
      },
      // 移除未实现的功能按钮
    },
    curWeek: -1,
    wkInterval: null,
    gdevicesMap: {},

    showCloudSyncDialog: false,
    popProcessVisible: false,
    popProcessVal: 0,
    isRelease:true,
  },

  // 处理设备电源状态变化
  handlePowerChange: function (e) {
    const {
      index,
      power
    } = e.detail
    const devices = [...this.data.devices] // Create a copy to avoid direct mutation
    devices[index].power = power
    this.setData({
        [`devices[${index}].power`]: power, // Target update specific device power
      },
      () => {
        wx.setStorageSync('devices', this.data.devices) // Update local storage
      }
    )
  },

  // 处理设备删除
  handleDeleteDevice: function (e) {
    const {
      index
    } = e.detail
    const devices = [...this.data.devices]
    const device = devices[index] // Get the device to be deleted
    devices.splice(index, 1)
    this.setData({
      devices: devices, // Update devices array directly
    })
    storageService.removeDevice(device.deviceId)
  },

  // 处理设备总开关状态变化
  handleSwitchChange: function (e) {
    const {
      type,
      value,
      index
    } = e.detail
    if (type === 'total') {
      const devices = [...this.data.devices]
      const device = devices[index] // **先获取设备对象**
      const deviceId = device.deviceId
      const updateData = {
        [`devices[${index}].totalSwitch`]: value
      }
      this.setData({
        [`devices[${index}].chgStatus`]: false
      })
      if (value) { //开启
        //按最后一次手动操作数据开启
        const valData = storageService.getLastManualVal(deviceId)
        if (valData.length > 0) {
          appInstance.sendMtMsg(device.topicSend, "chgValAll1", valData);
          const vArr = valData.map(obj => {
            return obj.v;
          })
          const child = this.selectComponent("#card" + deviceId);
          child.initVal({
            msg: vArr.join(";")
          })
        }
      } else { //关闭
        if (!device.isManualMode) {
          appInstance.sendMtMsg(device.topicSend, "chgAutoRun", 0);
          //停止本地行程、禁用相关已启用数据
          storageService.saveLightModeState(deviceId, "manual")
          playerModeService.disablePlayerTimerTasks(deviceId)
          advancedModeService.disableAdvancedCurves(deviceId)
        }
        const mqttData = []
        const channels = storageService.getDeviceChannels(deviceId)
        channels.forEach(ele => {
          mqttData.push({
            "n": ele.n,
            "v": 0
          })
        })
        appInstance.sendMtMsg(device.topicSend, "chgValAll1", mqttData);
        const child = this.selectComponent("#card" + deviceId);
        child.initVal({
          msg: "0;0;0;0;0;0;0;0;0;0;0;0"
        })
        this.changeStartEndTimeById(deviceId, null)
      }
      this.setData(updateData)
      const $t = this
      setTimeout(() => {
        $t.setData({
          [`devices[${index}].chgStatus`]: true
        })
        appInstance.sendMtMsg(device.topicSend, "online", null);
        appInstance.sendMtMsg(device.topicSend, "getVal", null);
      }, 500)
    }
  },
  // 处理设备总开关状态变化
  handleSwitchDbChange: function (e) {
    const {
      type,
      value,
      index
    } = e.detail
    if (type === 'total') {
      const devices = [...this.data.devices]
      const device = devices[index] // **先获取设备对象**
      const updateData = {
        [`devices[${index}].totalSwitch`]: value
      }
      this.setData({
        [`devices[${index}].chgStatus`]: false
      })

      if (comm.isEmpty(storageService.getTmpSynced(device.deviceId))) {
        this.showToast("请先同步临时配置到设备...");
        return;
      }
      if (value) { //开启
        appInstance.sendMtMsg(device.topicSend, "handOn", null);
        this.showToast("临时开灯命令已发送...");
      } else { //关闭
        appInstance.sendMtMsg(device.topicSend, "handOff", null);
        this.showToast("临时关灯命令已发送...");
      }
      this.setData(updateData)
      const $t = this
      setTimeout(() => {
        $t.setData({
          [`devices[${index}].chgStatus`]: true
        })
        appInstance.sendMtMsg(device.topicSend, "online", null);
        appInstance.sendMtMsg(device.topicSend, "getVal", null);
      }, 500)
    }
  },

  // 处理设备名称变更
  handleNameChange: function (e) {
    const {
      index,
      name
    } = e.detail
    this.setData({
        [`devices[${index}].name`]: name,
      },
      () => {
        storageService.saveDeviceInfo(this.data.devices[index].deviceId, this.data.devices[index])
      }
    )
  },

  handleSubButton: function (e) {
    if (!this.data.buttonHandlers) {
      console.error('buttonHandlers未初始化')
      return
    }
    const index = e.detail.index
    const handler = this.data.buttonHandlers[index]
    if (typeof handler === 'function') {
      handler.call(this)
    } else {
      console.warn('未找到对应的按钮处理函数:', index)
    }
  },

  // 处理设备总开关状态变化
  handleGroupSwitchChange: function (e) {
    const {
      type,
      value,
      index
    } = e.detail
    if (type === 'total') {
      const groups = [...this.data.groups]
      const group = groups[index] // **先获取设备对象**
      const groupId = group.deviceId
      const updateData = {
        [`groups[${index}].totalSwitch`]: value
      }
      const devices = storageService.batchGetDeviceInfo(group.deviceIds)
      if (value) { //开启
        //按最后一次手动操作数据开启
        const valData = storageService.getLastManualVal(groupId)
        if (valData.length > 0) {
          devices.forEach(device => {
            appInstance.sendMtMsg(device.topicSend, "chgValAll1", valData);
          })
        }
      } else { //关闭
        if (!group.isManualMode) {
          devices.forEach(device => {
            appInstance.sendMtMsg(device.topicSend, "chgAutoRun", 0);
          })
          //停止本地行程、禁用相关已启用数据
          storageService.saveLightModeState(groupId, "manual")
          playerModeService.disablePlayerTimerTasks(groupId)
          advancedModeService.disableAdvancedCurves(groupId)
        }
        const mqttData = []
        const channels = storageService.getDeviceChannels(groupId)
        channels.forEach(ele => {
          mqttData.push({
            "n": ele.n,
            "v": 0
          })
        })
        devices.forEach(device => {
          appInstance.sendMtMsg(device.topicSend, "chgValAll1", mqttData);
        })
        const child = this.selectComponent("#card" + groupId);
        child.initVal({
          msg: "0;0;0;0;0;0;0;0;0;0;0;0"
        })
        this.changeStartEndTimeById(groupId, null)
      }
      this.setData(updateData)
    }
  },
  // 处理设备总开关状态变化
  handleGroupSwitchDbChange: function (e) {
    const {
      type,
      value,
      index
    } = e.detail
    if (type === 'total') {
      const groups = [...this.data.groups]
      const group = groups[index] // **先获取设备对象**
      const groupId = group.deviceId
      const updateData = {
        [`groups[${index}].totalSwitch`]: value
      }
      if (comm.isEmpty(storageService.getTmpSynced(groupId))) {
        this.showToast("请先同步临时配置到设备...");
        return;
      }
      const devices = storageService.batchGetDeviceInfo(group.deviceIds)
      if (value) { //开启
        devices.forEach(device => {
          appInstance.sendMtMsg(device.topicSend, "handOn", null);
        })
        this.showToast("临时开灯命令已发送...");
      } else { //关闭
        devices.forEach(device => {
          appInstance.sendMtMsg(device.topicSend, "handOff", null);
        })
        this.showToast("临时关灯命令已发送...")
      }
      this.setData(updateData)
    }
  },

  // 处理编组名称变更
  handleGroupNameChange: function (e) {
    const {
      index,
      name,
      isGroup
    } = e.detail
    if (isGroup) {
      this.setData({
          [`groups[${index}].name`]: name,
        },
        () => {
          wx.setStorageSync('groups', this.data.groups)
        }
      )
    }
  },

  // 处理删除编组
  handleDeleteGroup: function (e) {
    const {
      index
    } = e.detail
    const groups = [...this.data.groups]
    const group = groups[index]
    groups.splice(index, 1)
    const idMap = {}
    group.deviceIds.forEach(id => {
      idMap[id] = 1
    })
    const devices = [...this.data.devices]
    devices.forEach(ele => {
      if (idMap[ele.deviceId] != undefined) {
        ele.inGroup = false
        ele.groupId = null
        delete this.data.gdevicesMap[ele.deviceId]
      }
    })

    this.setData({
      groups: groups,
      devices: devices,
    })
    // 使用存储服务恢复设备状态并删除编组
    storageService.restoreDevicesOnGroupDelete(group.deviceId)
  },

  onLoad: function (options) {
    console.log("index onLoad...")
    this.setData({
      isRelease:appInstance.globalData.isRelease
    })
    this.init()
    //设备激活
    if (appInstance.globalData.isRelease) {
      const activeIds = storageService.getActiveIds()
      if (activeIds.length > 0) {
        comm.httpGet("/device/active?ids=" + activeIds.join(':'), function (res) {
          storageService.removeActiveIds()
        })
      }
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    console.log("index onReady...")
  },

  onShow: function () {
    console.log("index onShow...")
    const $t = this;
    wx.$event.on("status", this, (obj) => {
      $t.chgStatus(obj);
    });
    wx.$event.on("getVal", this, (obj) => {
      $t.chgVal(obj);
    });
    wx.$event.on("EventOnline", this, (obj) => {
      $t.changeOnline(1, obj);
    });
    wx.$event.on("EventOffline", this, (obj) => {
      $t.changeOnline(0, obj);
    });

    this.getNowWeek();
    for (var i = 0; i < this.data.devices.length; i++) {
      let entityId = this.data.devices[i].deviceId
      let data = storageService.getScheduleInfo(entityId)
      this.changeStartEndTime(i, data)
      let isManualMode = storageService.isManualModeState(entityId)
      this.data.devices[i].isManualMode = isManualMode
      if (this.data.devices[i].online == undefined) {
        this.data.devices[i].online = 0
      }
    }
    this.setData({
      devices: this.data.devices
    })
    appInstance.globalData.isAdding = false;
    appInstance.mqttConnect();
    if (storageService.getRefreshDevicesFlag()) {
      this.init()
    }
    if (appInstance.checkMqttConnected()) {
      this.data.devices.forEach(device => {
        appInstance.sendMtMsg(device.topicSend, "online", null);
        appInstance.sendMtMsg(device.topicSend, "getVal", null);
      })
    }
    this.initOnline()
  },

  onHide: function () {
    console.log("index onHide...")
    wx.$event.remove("status", this);
    wx.$event.remove("getVal", this);
    wx.$event.remove("EventOnline", this);
    wx.$event.remove("EventOffline", this);

    clearInterval(this.data.wkInterval);
    this.data.wkInterval = null;

    // 页面隐藏时执行
    // 确保页面隐藏时收起菜单
    if (this.data.isExpanded) {
      this.setData({
        isExpanded: false,
      })
    }
  },

  init() {
    let dids = storageService.getDeviceIds()
    let devices = [];
    let topicSubArr = [];
    for (var i = 0; i < dids.length; i++) {
      let dobj = storageService.getDeviceInfo(dids[i])
      dobj.chgStatus = true;
      devices.push(dobj);
      topicSubArr.push({
        topicSend: dobj.topicSend,
        topicSub: dobj.topicSub
      });
    }
    const groups = storageService.getGroups()
    const gdevicesMap = {}
    for (let i = 0; i < groups.length; i++) {
      const group = groups[i]
      const onlines = []
      for (let j = 0; j < group.deviceIds.length; j++) {
        onlines.push(0)
        gdevicesMap[group.deviceIds[j]] = {
          gidx: i,
          didx: j,
        }
      }
      group.onlines = onlines
    }

    this.setData({
      devices: devices,
      groups: groups,
      gdevicesMap: gdevicesMap
    });
    appInstance.mtSubscribe(topicSubArr);
  },

  chgStatus(obj) {
    for (var i = 0; i < this.data.devices.length; i++) {
      if (this.data.devices[i].topicSub == obj.topic && this.data.devices[i].chgStatus) {
        let data = {}
        if (!this.data.devices[i].inGroup) {
          let str3 = "devices[" + i + "].fanStatus";
          let str4 = "devices[" + i + "].temperature";
          data = {
            [str3]: obj.msg["fanStarted"] != undefined && obj.msg["fanStarted"] == "1" ? "07" : "0",
            [str4]: obj.msg["tempNow"],
          }
          let str5 = "devices[" + i + "].totalSwitch";
          data[[str5]] = obj.msg["hasV"] == "1"
        }
        this.setData(data);
        break;
      }
    }
  },

  chgVal(obj) {
    for (var i = 0; i < this.data.devices.length; i++) {
      if (this.data.devices[i].topicSub == obj.topic && this.data.devices[i].chgStatus) {
        const device = this.data.devices[i]
        const child = this.selectComponent("#card" + device.deviceId);
        child.initVal(obj)
        if (!device.inGroup) {
          let totalSwitch = 0
          const valArr = obj.msg.split(';');
          for (var n = 0; n < valArr.length; n++) {
            if (parseInt(valArr[n]) > 0) {
              totalSwitch = 1
              break
            }
          }
          if (totalSwitch !== device.totalSwitch) {
            let data = {}
            const str5 = "devices[" + i + "].totalSwitch";
            data[[str5]] = totalSwitch
            this.setData(data)
          }
        }
        break;
      }
    }
  },

  initOnline() {
    for (var i = 0; i < this.data.devices.length; i++) {
      let obj = this.data.devices[i];
      if (!obj.chgStatus) {
        continue;
      }
      this.changeOnline0(appInstance.checkIsOnline(obj.topicSub) ? 1 : 0, obj, i)
    }
  },
  changeOnline(isOnline, topic) {
    for (var i = 0; i < this.data.devices.length; i++) {
      let obj = this.data.devices[i];
      if (obj.topicSub != topic || !obj.chgStatus) {
        continue;
      }
      this.changeOnline0(isOnline, obj, i)
    }
  },
  changeOnline0(isOnline, device, i) {
    if (device.online === isOnline) {
      return
    }
    let str2 = "devices[" + i + "].online";
    const data = {}
    data[[str2]] = isOnline
    if (device.inGroup) {
      const ginfo = this.data.gdevicesMap[device.deviceId]
      if (ginfo) {
        let gstr1 = "groups[" + ginfo.gidx + "].onlines[" + ginfo.didx + "]"
        data[[gstr1]] = isOnline
      }
    }
    this.setData(data);
  },
  getNowWeek() {
    const currentDate = new Date();
    let currentDay = currentDate.getDay();
    if (currentDay == 0) {
      currentDay = 6;
    } else {
      currentDay--;
    }
    //console.log(currentDay);
    if (this.data.curWeek != currentDay) {
      this.setData({
        curWeek: currentDay
      })
    }
  },
  changeStartEndTime(idx, data) {
    console.log("changeStartEndTime", idx, data)
    let startTime = "--:--"
    let endTime = "--:--"
    try {
      if (comm.isEmptyObj(data)) {
        return
      }
      let tlsArr = data.tls
      let weekArr = data.w
      let index = weekArr[this.data.curWeek]
      if (index < 0) {
        return
      }
      let arr = tlsArr[index]
      let min = 240000
      let max = 0
      for (var i = 0; i < arr.length; i++) {
        for (var j = 0; j < arr[i].length; j++) {
          if (arr[i][j][0] < min) {
            min = arr[i][j][0]
          }
          if (arr[i][j][0] > max) {
            max = arr[i][j][0]
          }
        }
      }

      let minH = parseInt(min / 10000)
      let minM = (min % 10000) / 100
      let maxH = parseInt(max / 10000)
      let maxM = (max % 10000) / 100
      if (minH < 10) {
        minH = "0" + minH
      }
      if (minM < 10) {
        minM = "0" + minM
      }
      if (maxH < 10) {
        maxH = "0" + maxH
      }
      if (maxM < 10) {
        maxM = "0" + maxM
      }
      startTime = minH + ":" + minM
      endTime = maxH + ":" + maxM
    } finally {
      this.setData({
        [`devices[${idx}].startTime`]: startTime,
        [`devices[${idx}].endTime`]: endTime
      })
    }
  },
  changeStartEndTimeById(deviceId, data) {
    let idx = -1;
    for (var i = 0; i < this.data.devices.length; i++) {
      if (this.data.devices[i].deviceId == deviceId) {
        idx = i;
        break;
      }
    }
    if (idx < 0) {
      return;
    }
    this.changeStartEndTime(idx, data)
  },

  handleSyncClose() {
    this.setData({
      showCloudSyncDialog: false
    })
  },
  showSyncUpConfirm() {
    const $t = this
    wx.showModal({
      title: '同步数据',
      content: '确定要同步配置到云端？',
      success: res => {
        if (res.confirm) {
          $t.beginSyncUp();
        }
      },
    })
  },
  showSyncDownConfirm() {
    const $t = this
    wx.showModal({
      title: '恢复数据',
      content: '将覆盖本地配置，确定要从云端同步？',
      success: res => {
        if (res.confirm) {
          wx.showLoading({
            title: '同步中......',
            mask: true,
            success: function () {
              $t.syncDown();
            }
          })
        }
      },
    })
  },
  beginSyncUp() {
    const openid = storageService.getOpenid()
    if (comm.isEmpty(openid)) {
      this.showToast("请先登录");
      return
    }
    const rArr = storageService.genBackupAllData()
    if (rArr.length == 0) {
      this.showToast("没有设备需要同步！");
      return
    }
    this.setData({
      popProcessVisible: true,
      popProcessVal: 0
    });
    let str = JSON.stringify(rArr);
    var pArr = [];
    while (true) {
      if (str.length > 1024) {
        pArr.push(str.substring(0, 1024));
        str = str.substring(1024);
      } else {
        pArr.push(str);
        break;
      }
    }
    this.syncObj = {
      openid: openid,
      cfgStrArr: pArr,
      key: parseInt(Math.random() * 10000000) + "",
      now: 1,
      total: pArr.length
    };
    this.sysnUp();
  },
  sysnUp() {
    const $t = this;
    const data = {
      openid: this.syncObj.openid,
      cfgStr: this.syncObj.cfgStrArr[this.syncObj.now - 1],
      key: this.syncObj.key,
      now: this.syncObj.now,
      total: this.syncObj.total
    };
    comm.httpPost("/cfgSync/syncUp", data, function () {
      if ($t.syncObj.now < $t.syncObj.total) {
        $t.syncObj.now++;
        $t.setData({
          popProcessVal: (parseFloat($t.syncObj.now * 100) / $t.syncObj.total).toFixed(2)
        });
        $t.sysnUp();
      } else {
        $t.syncObj = null;
        $t.setData({
          popProcessVisible: false
        });
        $t.showToast("同步完成");
      }
    }, function (errMsg) {
      $t.syncObj = null;
      $t.setData({
        popProcessVisible: false
      });
      $t.showToast(errMsg);
    });
  },
  syncDown() {
    const $t = this;
    const openid = storageService.getOpenid()
    if (comm.isEmpty(openid)) {
      this.showToast("请先登录");
      return;
    }
    comm.httpGet("/cfgSync/syncDown?openid=" + openid, function (res) {
      const cfgArr = JSON.parse(res.data.cfgStr);
      storageService.restoreBackupAllData(cfgArr)
      wx.hideLoading();
      $t.showToast("同步完成，即将重新加载页面！");
      setTimeout(() => {
        wx.redirectTo({
          url: "/pages/splash/splash"
        })
      }, 1000)
    }, function (errMsg) {
      wx.hideLoading();
      $t.showToast("获取失败");
    });
  },


  showToast(msg) {
    wx.showToast({
      title: msg,
      icon: 'none',
    })
  },

  onUnload: function () {
    console.log("index onUnload...")
  },


  test(){
    wx.redirectTo({
      url: '/pages/test/test',
      fail: err => {
        console.error('redirectTo 失败，尝试 switchTab:', err)
      },
    })
  },


})